package sitesettinghandler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"path"
	"strings"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/paysetting"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
)

//支付配置列表
func PaySettingList(c *gin.Context) {
	param := &struct {
		BaseListReq request.BaseListReq
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//获取数据
	data := dao.NewSiteSettingDao().PaySettingListDao(&param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data.Data)(ServerError)
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

//支付配置编辑
func PaySettingEdit(c *gin.Context) {
	param := &paysetting.PaySetting{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("修改成功", CodeUpdateSuccess, dao.NewSiteSettingDao().PaySettingEditDao(param.Id, param).Unwrap())(OK)
}

//支付配置新增
func PaySettingSave(c *gin.Context) {
	param := &paysetting.PaySetting{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("新增成功", CodeUpdateSuccess, dao.NewSiteSettingDao().PaySettingSaveDao(param).Unwrap())(OK)
}

//支付配置删除
func PaySettingDelete(c *gin.Context) {
	param := &struct {
		Id int `json:"id"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("删除成功", CodeUpdateSuccess, dao.NewSiteSettingDao().PaySettingDeleteDao(param.Id).Unwrap())(OK)
}

//支付证书路径上传
func PayCertsPathUpload(c *gin.Context) {
	file, err := c.FormFile("file")

	if err != nil {
		Response(c)("上传失败!请上传文件", CodeError, nil)(Error)
		return
	}

	//imgType := []string{"image/bmp", "image/png", "image/gif", "image/jpg", "image/jpeg", "image/pjpeg", "image/x-png"}
	fileExt := strings.ToLower(path.Ext(file.Filename))
	// 判断 文件类型
	//if !utils.Contains([]string{}, file.Header.Get("Content-Type")) {
	//	Response(c)("上传失败!文件类型错误", CodeError, nil)(Error)
	//}
	// 判断 文件后缀
	if fileExt != ".p12" && fileExt != ".pem" {
		Response(c)("上传失败!p12,pem文件", CodeError, nil)(Error)
		return
	}
	// 判断 文件大小 1024*1024*10
	if file.Size > 10485760 {
		Response(c)("上传失败!只允许小于10M的文件", CodeError, nil)(Error)
		return
	}
	fileName := file.Filename
	var fileDir string

	fileDir = global.Cfg.Wx.CertPath
	filePath := fmt.Sprintf("%s%s", fileDir, fileName)

	// 保存文件
	dingo.ErrorIf(c.SaveUploadedFile(file, filePath)).Unwrap()
	//param := &paysetting.PaySetting{}
	////入库
	//param.CertsPath = filePath
	//dao.NewSiteSettingDao().PaySettingEditDao(id, param).Unwrap()

	//响应给前端
	Response(c)("", CodeSuccess, filePath)(OK)

}
